package com.quanyan.club.service.impl;

import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.TbClub;
import com.quanyan.club.entity.db.TbClubExample;
import com.quanyan.club.entity.db.TbClubMember;
import com.quanyan.club.entity.db.TbClubMemberExample;
import com.quanyan.club.entity.vo.resp.RespClubActivityMember;
import com.quanyan.club.entity.RespClubMember;
import com.quanyan.club.entity.vo.resp.RespClubWeekTask;
import com.quanyan.club.mapper.ClubActivityMapper;
import com.quanyan.club.mapper.TbClubActivityMapper;
import com.quanyan.club.mapper.TbClubMapper;
import com.quanyan.club.mapper.TbClubMemberMapper;
import com.quanyan.club.service.*;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.place.client.PlaceClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yue.yuan on 2016/9/26.
 */
@Service("clubTaskService")
public class ClubTaskServiceImpl implements ClubTaskService {

    private static Logger logger = LoggerFactory.getLogger(ClubTaskServiceImpl.class);

    @Autowired
    private PlaceClient placeClient;

    @Autowired
    private TbClubActivityMapper tbClubActivityMapper;

    @Autowired
    private TbClubMapper tbClubMapper;

    @Autowired
    private TbClubMemberMapper clubMemberMapper;

    @Autowired
    private ClubMemberService clubMemberService;

    @Autowired
    private ClubActivityService clubActivityService;

    @Autowired
    private ActivityOpenService activityOpenService;

    @Autowired
    private ClubActivityMapper clubActivityMapper;
    @Autowired
    private ActivityAccountService activityAccountService;

    @Override
    public RespClubWeekTask getClubWeekTaskById(Integer clubId, int uid)
    {
        //本周的开始和结束时间
        Date startTime = DateUtils.getTimesWeekmorning(new Date());
        Date endTime = DateUtils.getTimesWeeknight(new Date());
        TbClub club = tbClubMapper.selectByPrimaryKey(clubId);
        if(club.getClubType() > 4 || club.getClubType() == 0)
        {
            RespClubWeekTask respClubWeekTask = new RespClubWeekTask();
            respClubWeekTask.setActivityCount(0);
            respClubWeekTask.setPersonTimes(0);
            respClubWeekTask.setPlaceHour(0.00);
            respClubWeekTask.setActivityTargetCount(0);
            respClubWeekTask.setPersonTargetTimes(0);
            respClubWeekTask.setPlaceTargetHour(0.00);
            return respClubWeekTask;
        }
        //该俱乐部的管理层
        List<RespClubMember> admins = clubMemberService.listClubAdministors(uid, clubId);
        if(null == admins || admins.size() == 0)
        {
             return null;
        }
        //管理层订场有效时间
        Double placeHour = 0.00;
        for(RespClubMember member : admins)
        {
            if(member.getUid() == uid)
            {
                if(validClub(uid, true, clubId))
                {
                    Double p = placeClient.getUserPlaceHours(uid, startTime, endTime);
                    if(p != null)
                    {
                        placeHour += p;
                    }
                }
            }
            else
            {
                if(validClub(uid, false, clubId))
                {
                    if(validClub(uid, true, clubId))
                    {
                        Double p = placeClient.getUserPlaceHours(uid, startTime, endTime);
                        if(p != null)
                        {
                            placeHour += p;
                        }
                    }
                }
            }
        }
        int activityCount = 0;
        int personTimes = 0;
        //该俱乐部本周开始的活动个数
        List<Integer> activitiyIds = getCycleActivityIds(clubId, "taskWeek");
        if(null != activitiyIds && activitiyIds.size() > 0)
        {
            activityCount = activitiyIds.size();
            for(int activityId : activitiyIds)
            {
                personTimes += getActivityCounts(activityId);
            }
        }
        RespClubWeekTask respClubWeekTask = new RespClubWeekTask();
        respClubWeekTask.setActivityCount(activityCount);
        respClubWeekTask.setPersonTimes(personTimes);
        respClubWeekTask.setPlaceHour(placeHour);

        setTarget(respClubWeekTask, club.getClubType());
        return respClubWeekTask;
    }

    private void setTarget(RespClubWeekTask respClubWeekTask, int categoryId)
    {

        if(categoryId == 1)
        {
            //篮球
            respClubWeekTask.setActivityTargetCount(2);
            respClubWeekTask.setPersonTargetTimes(12);
            respClubWeekTask.setPlaceTargetHour(4.00);
        }
        else if(categoryId == 2)
        {
            //羽毛球
            respClubWeekTask.setActivityTargetCount(3);
            respClubWeekTask.setPersonTargetTimes(18);
            respClubWeekTask.setPlaceTargetHour(6.00);
        }
        else if(categoryId == 3)
        {
            //足球
            respClubWeekTask.setActivityTargetCount(2);
            respClubWeekTask.setPersonTargetTimes(20);
            respClubWeekTask.setPlaceTargetHour(4.00);
        }
        else if(categoryId == 4)
        {
            //网球
            respClubWeekTask.setActivityTargetCount(2);
            respClubWeekTask.setPersonTargetTimes(8);
            respClubWeekTask.setPlaceTargetHour(4.00);
        }
    }

    //获取该俱乐部本周/本月开始的活动个数
    /**
     * taskWeek,taskMonth
     * @param clubId
     * @param taskCycle
     * @return
     */
    public List<Integer> getCycleActivityIds(Integer clubId, String taskCycle)
    {
        List<Integer> activityIds = clubActivityMapper.selectEffectiveActivityByClub(clubId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(taskCycle, 1L);
        logger.warn("该俱乐部的有效活动为:{}", activityIds);
        List<Integer> ids = activityOpenService.queryActivityIdsByCondition(activityIds, map);
        logger.warn("俱乐部ID为：" + clubId + "的周期内开始的有效活动有{}", ids);
        return ids;
    }

    //上一周的日常数据
    public List<Integer> getCycleActivityIdsInTime(Integer clubId,String taskCycle)
    {
        List<Integer> activityIds = clubActivityMapper.selectEffectiveActivityByClubInTime(clubId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(taskCycle, 1L);
        logger.warn("该俱乐部的有效活动为:{}", activityIds);
        List<Integer> ids = activityOpenService.queryActivityIdsByCondition(activityIds, map);
        logger.warn("俱乐部ID为：" + clubId + "的周期内开始的有效活动有{}", ids);
        return ids;
    }
     //每天的数据
    public List<List<Integer>> getEveryDayActivityCount(Integer clubId,Date trendStartTime,Date trendEndTime)
    {
        List<List<Integer>> activityIds =
                clubActivityMapper.selectEffectiveActivityByEveryDay(clubId,trendStartTime,trendEndTime);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("start", trendStartTime);
        map.put("end", trendEndTime);
        logger.warn("每天俱乐部的有效活动为:{}", activityIds);
        List<List<Integer>> ids = null;
        if(!activityIds.isEmpty() &&activityIds!=null &&activityIds.size()>0) {
             ids = activityOpenService.queryEveryDayActivityByCondition(activityIds, map);
        }
        logger.warn("俱乐部ID为：" + clubId + "的周期内开始的有效活动有{}", ids);
        return ids;
    }
    //获取线上报名总人数
    private int getActivityCounts(int activityId)
    {
        int count = 0;
        APIResponse<List<RespClubActivityMember>> result =
                activityAccountService.getActivityMemberList(activityId, null);
        List<RespClubActivityMember> memberList = result.getData();
        count += getCount(memberList);
        if(null != memberList && memberList.size() > 0)
        {
            for (RespClubActivityMember member : memberList)
            {
                List<RespClubActivityMember> replaces = member.getReplaceMembers();
                count += getCount(replaces);
            }
        }
        logger.warn("活动ID为:" + activityId + "的线上报名人数为" + count);
        return count;

    }

    private int getCount(List<RespClubActivityMember> list)
    {
        if(null == list || list.size() == 0)
        {
            return 0;
        }
        else
        {
            return list.size();
        }
    }

    //校验是否是第一个有效俱乐部
    private boolean validClub(int uid, boolean isCreator, Integer clubId)
    {
        int firstClubId = 0;
        if(isCreator)
        {
            firstClubId = getFirstCreateClubId(uid);
            logger.warn("用户ID为：" + uid + "的第一个创建俱乐部ID为：" + firstClubId);
        }
        else
        {
            firstClubId = getAdminFirstJoinClubId(uid);
            logger.warn("用户ID为：" + uid + "的第一个管理的俱乐部ID为：" + firstClubId);
        }
        return clubId == firstClubId;
    }

    //获取第一个创建的有效俱乐部
    private int getFirstCreateClubId(int uid)
    {
        TbClubExample clubExample = new TbClubExample();
        clubExample.createCriteria().andUidEqualTo(uid)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
        clubExample.setLimit(Limit.buildLimit(1, 1));
        List<TbClub> clubList = tbClubMapper.selectByExample(clubExample);
        if(null != clubList && clubList.size() == 1)
        {
            TbClub club = clubList.get(0);
            return club.getId();
        }
        logger.warn("数据异常，没有查到该用户创建的俱乐部,用户ID：" + uid);
        return 0;
    }

    //获取第一个管理的俱乐部
    private int getAdminFirstJoinClubId(int uid)
    {
        TbClubMemberExample clubMemberExample = new TbClubMemberExample();
        clubMemberExample.createCriteria().andUidEqualTo(uid)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO).andPriorityNotEqualTo(4);
        clubMemberExample.setLimit(Limit.buildLimit(1, 1));
        List<TbClubMember> clubMembers = clubMemberMapper.selectByExample(clubMemberExample);
        if(null != clubMembers && clubMembers.size() == 1)
        {
            TbClubMember clubMember = clubMembers.get(0);
            return clubMember.getClubId();
        }
        logger.warn("数据异常，没有查到该用户作为管理者的俱乐部,用户ID：" + uid);
        return 0;
    }


}
